<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" @submit.native.prevent>
      <dynamic-search-form
        inline
        :formData="formData"
        :form="queryParams"
        :pageSize="this.$store.state.user.pageSize||30"
        @postForm="postData"
        v-if="this.search!='false'"
      >
      </dynamic-search-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <div
            v-for="(toolbar, index) in toolbarData"
            :key="index"
            style="display: inline-block"
          >
            <template
              v-if="
                (toolbar.info.display == 0 && toolbar.data.length >= 4) ||
                toolbar.info.display == 2
              "
            >
              <el-dropdown
                placement="bottom-start"
                style="padding: 0; margin-right: 10px; margin-left: 10px"
              >
                <el-button type="primary" size="mini">
                  <i :class="toolbar.info.icon"></i>
                  {{ toolbar.info.description }}
                  <i class="el-icon-arrow-down"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(btn, key) in toolbar.data.filter(
                      (item) => item.status === '1' && item.location === '2'
                    )"
                    :key="key"
                  >
                    <el-button
                      size="mini"
                      type="text"
                      :icon="btn.icon"
                      @click="clickEvent(btn)"
                      :disabled="
                        btn.show != null &&
                        btn.show != undefined &&
                        btn.show != ''
                          ? !dynamicEval($data, btn.show)
                          : false
                      "
                      v-preventReClick
                      >{{ btn.name }}</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template
              v-if="
                (toolbar.info.display == 0 && toolbar.data.length < 4) ||
                toolbar.info.display == 1
              "
            >
              <div
                v-for="(btn, index) in toolbar.data"
                :key="index"
                style="display: inline-block; margin: 0 3px"
              >
                <template v-if="btn.name == '全编辑' && getEditForm(btn.url)">
                  <el-button
                    v-if="!editall"
                    :type="btn.styleType"
                    :icon="btn.icon"
                    size="mini"
                    @click="clickEvent(btn)"
                    >{{ btn.name }}
                  </el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="subEditAll()"
                    v-if="editall"
                    >保存</el-button
                  >
                  <el-button
                    type="info"
                    size="mini"
                    @click="cancelEditAll()"
                    v-if="editall"
                    >取消</el-button
                  >
                </template>
                <template v-else>
                  <el-button
                    v-if="btn.status === '1' && btn.location === '2'"
                    :type="btn.styleType"
                    :icon="btn.icon"
                    size="mini"
                    @click="clickEvent(btn)"
                    :disabled="
                      btn.show != null &&
                      btn.show != undefined &&
                      btn.show != ''
                        ? !dynamicEval($data, btn.show)
                        : false
                    "
                    v-preventReClick
                    >{{ btn.name }}
                  </el-button>
                </template>
              </div>
            </template>
          </div>
        </el-col>
      </el-row>
      <el-row style="max-height: 800px">
        <dynamic-tree-table
          ref="treeTable"
          v-if="type == 'tree_table'"
          :list="list"
          @openTable="openTable($event)"
          @handleSelectionChange="handleSelectionChange"
          @SetFlag="SetFlag()"
          :options="options"
          :columns="tableColumns"
          :operates="operates"
          :flag="flag"
          :diff="300"
          :scroll="'false'"
          :uncheck="exsitId"
          :defaultSelect="defaultSelect"
        >
        </dynamic-tree-table>
        <dynamic-split-tree-table
          ref="treeTable"
          v-else-if="type == 'split_tree_table'"
          :list="list"
          @openTable="openTable($event)"
          @handleSelectionChange="handleSelectionChange"
          @SetFlag="SetFlag()"
          :options="options"
          :columns="tableColumns"
          :operates="operates"
          :flag="flag"
          :diff="300"
          :scroll="'false'"
          :uncheck="exsitId"
          :expandUrl="expandUrl"
        >
        </dynamic-split-tree-table>
        <template v-else>
          <dynamic-table
            :list="list"
            @handleSelectionChange="handleSelectionChange"
            @openTable="openTable"
            :options="options"
            :columns="tableColumns"
            :operates="operates"
            :diff="300"
            :parent="this"
            :scroll="'false'"
            :uncheck="exsitId"
            :defaultSelect="defaultSelect"
          >
          </dynamic-table>
          <pagination
            v-show="submiturl != 'batch' && total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            layout="total, prev, pager, next,jumper"
          />
        </template>
      </el-row>
    </el-form>
    <div style="float: right; margin: 5px 0">
      <el-button
        type="primary"
        @click="submitForm"
        v-preventReClick
        v-if="!toolbar||toolbar.indexOf('restrain') == -1"
        >确 定</el-button
      >
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
<script>
import {
  getDataList,
  getConfigInfo,
  addData,
  getTableCol,
} from "@/api/dynamic/dynamic";
import { deepClone, filter2sub } from "@/utils";

export default {
  name: "dynamicFormTable",
  props: {
    form: Object,
    exsitId: Array,
    geturl: String,
    table: String,
    toolbar: String,
    command: String,
    submiturl: {
      type: String,
      default: ''
    },
    formtype: String,
    search:String,
    formMulti:{
      type: String,
      default: 'true'
    },
    defaultSelect:Object,
    expandUrl:''
  },
  components: {
    dynamicSearchForm:() => import("@/views/components/dynamicSearchForm"),
    dynamicTable:() => import("@/views/components/dynamicTable"),
    dynamicTreeTable:() => import("@/views/components/dynamicTreeTable"),
    dynamicSplitTreeTable:() => import("@/views/components/dynamicSplitTreeTable")
  },
  data() {
    return {
      formData: [],
      submitData: {},
      toolbarData: [],
      // 总条数
      total: 0,
      list: [],
      showlist: [],
      selected: [],
      ids: [],
      tableColumns: [],
      columns: [], // 需要展示的列
      rules: {},
      queryParams: {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
      },
      PLMqueryParams: {
        begin: 1,
        end: this.$store.state.user.pageSize||30,
      },
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: true, // 是否支持列表项选中功能
        expandColumn: "name",
      },
      operates: {
        // 列操作按钮
        width: 150,
        list: [],
      },
      type: "table",
      flag: true,
    };
  },
  created() {
    this.getConfig();
    // console.log(this.search)
    if(this.search=='false')
      this.getList();
  },
  methods: {
    /** 获取配置信息 */
    getConfig() {
      getConfigInfo({
        table: this.table,
        toolbar: this.toolbar,
        command: this.command,
        searchForm: (this.search!='false'?this.search:'full_search'),
      }).then((response) => {
        // this.formData = response.data.searchFormData;
        this.getFormData(response.data.searchFormData,true);
        this.toolbarData = response.data.toolbarData;
        this.operates.list = response.data.commandData;
        this.tableColumns = response.data.tableData;
      });
    },
    postData(val) {
      this.queryParams = {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
      };
      var keys = Object.keys(val);
      for (var i = 0; i < keys.length; i++) {
        this.$set(this.queryParams, keys[i], val[keys[i]]);
      }
      this.getList();
    },
    getList(geturl = "") {
      if (geturl == "" || typeof geturl != "string") geturl = this.geturl;
      if (this.submiturl && this.submiturl.indexOf("pmsbatch") > -1) {
        getTableCol({ table: geturl }).then((response) => {
          this.list = response.data.filter((item) => {
            if (item.className && item.className.indexOf("batch") > -1)
              return item;
          });
          this.total = 0;
        });
      } else {
        if (
          geturl.indexOf("line") > -1 ||
          geturl.indexOf("dispatchList") > -1 ||
          (this.formtype&&this.formtype.indexOf("tree_table")>-1)
        ) {
          this.type = this.formtype=="split_tree_table"?"split_tree_table":"tree_table";
          delete this.queryParams['pageNum'];
          delete this.queryParams['pageSize'];
        }
        if(geturl.indexOf('enovia')>-1){
          this.PLMqueryParams = {
            // loginUser: 'GDAdmin'
            loginUser: sessionStorage.getItem('loginUser')||this.$store.state.user.userid||'GDAdmin',
          };
          for(let index in this.queryParams){
            if(index!='pageNum'&&index!='pageSize'){
              this.PLMqueryParams[index] = this.queryParams[index];
            }
          }
          if(this.type=='table'){
            this.PLMqueryParams.begin = (this.queryParams.pageNum-1)*this.queryParams.pageSize+1
            this.PLMqueryParams.end = this.queryParams.pageNum*this.queryParams.pageSize
          }
          getDataList(geturl, this.PLMqueryParams).then((response) => {
            // response= response.replace(/\"/g,"'");
            response = JSON.parse(response)
            // console.log(JSON.parse(response))
            if (response.rows != undefined) {
              this.list = response.rows;
              if (this.type == "tree_table") {
                this.SortList(this.list);
                this.flag = true;
                if (geturl.indexOf("dispatchList") > -1) {
                  for (let item of this.list) {
                    if (JSON.stringify(item.params) != "{}") {
                      this.submitData[item.id] = {
                        id: item.id,
                        params: item.params,
                        projectid: this.$route.params.Id,
                      };
                    }
                  }
                }
              }
            } else{ 
              this.list = response.data;
              this.total = response.total;
            }
          });
        }else{
          getDataList(geturl, this.queryParams).then((response) => {
            if (response.rows != undefined) {
              this.list = response.rows;
              if (this.type == "tree_table") {
                // this.SortList(this.list);
                this.flag = true;
                if (geturl.indexOf("dispatchList") > -1) {
                  for (let item of this.list) {
                    if (JSON.stringify(item.params) != "{}") {
                      this.submitData[item.id] = {
                        id: item.id,
                        params: item.params,
                        projectid: this.$route.params.Id,
                      };
                    }
                  }
                }
              }
              this.total = response.total
            } else{ 
              this.list = response.data;
              this.total = response.total;
            }
          });
        }
      }
    },
    // 数据排序
    SortList(val) {
      val.sort(function (list1, list2) {
        let list1_rank = list1.rank ? list1.rank.trim().split(".") : [0];
        let list2_rank = list2.rank ? list2.rank.trim().split(".") : [0];
        for (let i = 0; ; i++) {
          if (list1_rank[i] == undefined && list2_rank[i] == undefined)
            return true;
          list1_rank[i] =
            list1_rank[i] == undefined ? 0 : Number(list1_rank[i]);
          list2_rank[i] =
            list2_rank[i] == undefined ? 0 : Number(list2_rank[i]);
          if (list1_rank[i] - list2_rank[i] != 0) {
            return list1_rank[i] - list2_rank[i];
          }
        }
      });
    },
    // 更新去除已存在数据
    updateData() {
      this.showlist = this.list.map((item) => {
        if (!this.exsitId.includes(item.id)) {
          return item;
        }
      });
    },
    // 只展示已选
    // onlyChecked(){
    //   if(this.only){
    //     this.showlist=this.list
    //   }else{
    //     this.showlist=this.selected
    //   }
    //   this.only=!this.only
    // },
    // 选中更改
    handleSelectionChange(selection) {
      this.selected = selection;
      this.ids = selection.map((item) => item.id);
    },
    // 取消按钮
    cancel() {
      this.$emit("topenChanged", false);
    },
    /** 提交按钮 */
    submitForm() {
      var route = this.getUrl(this.submiturl);
      if(this.ids.length==0 &&route.indexOf("batchAll") == -1 && route.indexOf("Matching") == -1&&route != "match"&&this.formMulti!='null'){
        this.msgInfo("请选择");
        return false
      }else{
        if (route) {
          if (route.indexOf("pmsbatch") > -1) {
            this.$emit("subBatch", this.selected);
            // this.$emit('loadingOpen')
            return true;
          }
          if (route == "match") {
            this.$emit("closeTable", this.selected);
            return true;
          }
          if (this.formMulti=='false') {
            if (this.ids.length > 1) {
              this.msgInfo("仅支持选择一项");
              return false;
            }
            // this.$emit('loadingOpen')
          }
          if (route.indexOf("batchAll") > -1 || route.indexOf("Matching") > -1) {
            if (JSON.stringify(this.submitData) != "{}") {
              this.$emit('loadingOpen')
              addData(route, Object.values(this.submitData))
                .then((response) => {
                  if (response.code === 200) {
                    this.msgSuccess(response.msg);
                    this.$emit("topenChanged", true);
                  }else{
                    this.$emit('loadingClose');
                  }
                })
                .catch(() => {
                  this.$emit("topenChanged", true);
                  this.$emit('loadingClose');
                });
            } else {
              this.msgInfo("无提交数据");
            }
            return;
          } else {
            if(route=='/deliverable/addPLMDeliverable'){
              this.form.source = 'plm'
            }
            this.$refs["form"].validate((valid) => {
              if (valid) {
                this.$emit('loadingOpen')
                this.form.ids = this.ids.join(",");
                addData(route, this.form)
                .then((response) => {
                  if (response.code === 200) {
                    this.msgSuccess(response.msg);
                    this.$emit("topenChanged", true);
                  }else{
                    this.$emit('loadingClose');
                  }
                })
                .catch(() => {
                  this.$emit("topenChanged", true);
                  this.$emit('loadingClose');
                });
              }
            });
          }
        } else {
          if(this.selected.length==0){
            this.msgInfo('请选择');
            return
          }
          if(this.formMulti=='false'&&this.selected.length>1){
            this.msgInfo('仅可选择一项')
            return
          }
          this.$emit('submit',this.selected)
        }
      }
    },
    clickEvent(btn) {
      this.updateIds();
      btn.sub = true;
      this.$emit("clickEvent", btn);
    },
    openTable(val) {
      val.sub = true;
      this.$emit("openTable", val);
    },
    updateIds() {
      this.$emit("updateIds", this.ids);
      if (this.ids.length > 0) {
        this.$emit("updateIds", this.ids);
      }
    },
    SetFlag() {
      this.flag = false;
    },
    //获取表单数据
    getFormData(formData, flag) {
      formData.forEach((item, index) => {
        if (
          item.componentType === "el-select" ||
          item.componentType === "el-selects" ||
          item.componentType === "el-radio" ||
          item.componentType === "el-checkbox-group"
        ) {
          if (
            item.prop === "policyid" ||
            item.prop === "stateid" ||
            item.prop === "ownerid"
          ) {
            formData[index].optionValue = optionData[item.optionValue];
          } else {
            if (
              this.tempDicts[item.prop] &&
              this.tempDicts[item.prop].length > 0
            ) {
              formData[index].optionValue = this.selectNormalizer(
                deepClone(this.tempDicts[item.prop])
              );
            } else {
              if (item.optionValue && item.optionValue.indexOf("url") > -1) {
                let url = this.getUrl(item.optionValue.split(":")[1]);
                getDataList(url).then((response) => {
                  if (response.code == 200) {
                    formData[index].optionValue = response.rows;
                  }
                });
              } else {
                this.getDicts(item.optionValue).then((response) => {
                  this.tempDicts[item.prop] = deepClone(response.data);
                  formData[index].optionValue = this.selectNormalizer(
                    response.data
                  );
                });
              }
            }
          }
        }
        if (item.componentType === "el-cascader") {
          let optionarr = item.optionValue.split("?");
          if (optionarr.length > 1) {
            this.optionNormalizer(optionData[optionarr[0]]);
            let typearr = [];
            optionData[optionarr[0]].forEach((titem) => {
              if (titem.value === parseInt(optionarr[1])) {
                typearr.push(titem);
                formData[index].optionValue = typearr;
              }
            });
          } else {
            formData[index].optionValue = this.optionNormalizer(
              optionData[item.optionValue]
            );
          }
        }
      });
      this.formData = formData;
      if (flag) {
        for (let item of formData) {
          if (this.queryParams[item.prop] == undefined && item.defaultValue) {
            this.$set(this.queryParams, item.prop, item.defaultValue);
          }
        }
      }
    },
    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel,
        };
      });
      return data;
    },
  },
};
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
.el-checkbox.el-checkbox__label {
  width: 100%;
}
.pagination-container {
  margin: 0 0 20px 0;
  height: 30px;
}
</style>

